import { defineComponent } from "vue";
import DialogBox from "@/components/DialogBox";
import ProTable from "@/components/ProTable/index.vue";
import { deepClone } from "@/utils/util";
import { setSensor } from "@/api/modules/model/sensor";
import { ElInput, ElMessage } from "element-plus";
const ParamSend = defineComponent({
	components: { ProTable },
	setup: (props, { expose }) => {
		const defaultData = reactive({
			visible: false,
			column: [
				{ label: "变量名称", prop: "label" },
				{ label: "变量标识", prop: "key" },
				{ label: "当前值", prop: "value" },
				{ label: "下发值", prop: "sendVal", width: "150px" }
			] as any,
			tableList: [] as any,
			detail: {} as any,
			getParamApi: null as any
		});
		const Init = (detail: any, list: any, backFn: any) => {
			defaultData.visible = true;
			defaultData.detail = detail;
			defaultData.tableList = deepClone(list);
			defaultData.getParamApi = backFn;
		};
		const commitParam = () => {
			const param = {} as any;
			defaultData.tableList.map((item: any) => {
				if (item.sendVal !== null && !item.sendVal !== undefined && item.sendVal !== "") {
					param[item.key] = item.type == "number" ? Number(item.sendVal) : item.sendVal;
				}
			});
			if (!Object.keys(param).length) {
				ElMessage.warning("请至少填写一个下发信息");
				return;
			}
			setSensor({
				idSn: defaultData.detail.sn,
				local: false,
				entire: false,
				data: param
			}).then((res: any) => {
				if (res.code == 200) {
					defaultData.visible = false;
					ElMessage.success("下发成功");
					defaultData.getParamApi?.();
				} else {
					ElMessage.error(res.message || "下发失败");
				}
			});
		};
		expose({
			Init
		});
		return () => {
			return (
				<DialogBox v-model:visible={defaultData.visible} title="参数下发" width="800px" onConfirm={commitParam}>
					<div style="height: 400px;">
						<ProTable
							toolButton={false}
							columns={defaultData.column}
							pagination={false}
							requestApi={() => {
								return {
									result: { datalist: defaultData.tableList }
								};
							}}
						>
							{{
								sendVal: (scope: any) => {
									return <ElInput v-model={scope.row.sendVal} />;
								}
							}}
						</ProTable>
					</div>
				</DialogBox>
			);
		};
	}
});
export default ParamSend;
